package com.weiyuwqj.api.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Date;
import java.util.UUID;

/**
 * Copyright 2015-2019 Yunfucloud technology co., Ltd.
 * Created by fuxx on 15/12/24.
 */
public class JwtUtils {

    public static String secretKey="ZC+BrFRngnZ8MBDJ9yjOpmlC1wEh+SebqbNTZ5IRUUOifGk" +
            "Ii81zas/+i1lFPPtjqVG/38UYnRiQZ9fFfcAsEw==";

    public static String generateSecretKey(){
        String secretKey="";
        String uuid=new BASE64Encoder().encode(UUID.randomUUID().toString().getBytes());
        secretKey=uuid;
        return secretKey;
    }

    public static Key generateKey(String secretKey){
        Key key=null;
        try{
            byte[] keyBytes=new BASE64Decoder().decodeBuffer(secretKey);
            key=new SecretKeySpec(keyBytes, SignatureAlgorithm.HS256.getJcaName());
        }catch (Exception e){

        }
        return  key;
    }

    public static Key decodeKey(String secretKey){
        Key key=null;
        try {
            byte[] keyBytes=new BASE64Decoder().decodeBuffer(secretKey);
            key=new SecretKeySpec(keyBytes, SignatureAlgorithm.HS256.getJcaName());
        }catch (Exception e){

        }
        return  key;
    }

    public static String token(String subject,String secretKey,Date date){
        Key key=decodeKey(secretKey);
        String token=Jwts.builder().setExpiration(date).setSubject(subject).signWith(SignatureAlgorithm.HS256, key).compact();
        String base64Token=new BASE64Encoder().encode(token.getBytes());
        base64Token=base64Token.replace('=','*');
        base64Token=base64Token.replace("\n","");
        base64Token=base64Token.replace("\r","");
        return base64Token;
    }

    public static String verify(String token,String secretKey)throws Exception{
        token=token.replace('*','=');
        Key key=decodeKey(secretKey);
        String decodeToken=new String(new BASE64Decoder().decodeBuffer(token));
        String subject=Jwts.parser().setSigningKey(key).parseClaimsJws(decodeToken).getBody().getSubject();
        return subject;
    }


    public static void main(String[] args) throws Exception {
        String key="RskqNRL0WSwwVYFbGWfu54/wNPdD0I1N9u+e1PbTZO3562zbk/LV95JvePbewf4QPYmqJ9WG9zpLXvZ" +
                "kgK3nf4eXw==MGVlOWQzZWUtZGRkYy00YTNkLTgzZjEtNTgyNWVmZWFmNDk0";

        String secretKey=JwtUtils.generateSecretKey();
        Date d=new Date();
        Date exp=DateUtils.addMinutes(d,60);
        String token=JwtUtils.token("40806",key,exp);
        System.out.println(key);
        System.out.println(token);

    }
}
